<?php

/**
 * Average studentactivity per company
 * @package ModuleStatistiques
 * @version 1.0b
 * @return JSON
 */

session_start();

// Configuration file
include '../../configuration.php';
// Functions
include '../../inc/functions.php';

// Checking if user is logged in
if (!CheckSession()):
	exit();
endif;

// Database connexion string
$db_str = "mysql:dbname=".$configuration['db'].";host=".$configuration['host'];

// Collecting numeric stats
try {
	
	// Connecting to database
	$db = new PDO($db_str, $configuration['user'], $configuration['pass']);
	
	// Query
	$sql  = 'SELECT ROUND(AVG(DATEDIFF(gotstudentactivity.to, gotstudentactivity.from)), 0) AS "DUREE", company.name AS "COMPANY", studentactivity.name AS "ACTIVITY" ';
	$sql .= 'FROM gotstudentactivity INNER JOIN company ON gotstudentactivity.companyId = company.companyId INNER JOIN studentactivity ON gotstudentactivity.studentactivityId = studentactivity.studentactivityId ';
	$sql .= 'GROUP BY company.name, studentactivity.name;';
	
	// Executing query
	$query = $db->prepare($sql);
	$query->execute();
	
	// Fetching data
	$result = $query->fetchAll(PDO::FETCH_ASSOC);
	
	// Rendering data
	$categories = $initiate = $series = Array();
	
	foreach ($result as $item) {
		if (!in_array($item['ACTIVITY'], $categories)) {
			array_push($categories, $item['ACTIVITY']);
			array_push($initiate, 0);
		}
	}
	
	foreach ($result as $item) {
		$k = 0;
		$size = count($series);
		while ($k < $size) {
			if ($series[$k]['name'] == $item['COMPANY'])
				break;
			++$k;
		}
		if ($k == $size)
			array_push($series, Array('name' => $item['COMPANY'], 'data' => $initiate));
		
		$k = 0;
		$size = count($series);
		$sizeCats = count($categories);
		for ($i = 0; $i < $sizeCats; ++$i) {
			if ($item['ACTIVITY'] == $categories[$i]) {
				while ($k < $size) {
					if ($series[$k]['name'] == $item['COMPANY'])
						$series[$k]['data'][$i] = intval($item['DUREE']);
					++$k;
				}
			}
		}
	}
	
	echo json_encode($series);
	
} catch (Exception $e) {
	echo $e->getMessage();
}

?>